package cn.edu.zafu.bigdata.xct.wlbc;

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String[] args) {
        int port = 1234; // 设置服务端的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务端启动，等待客户端连接...");

            // 服务器无限循环等待客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端 " + clientSocket.getRemoteSocketAddress() + " 已连接");

                // 创建输入输出流
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                // 循环读取客户端发送的消息并回复
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("从客户端收到消息: " + inputLine);

                    // 发送消息给客户端
                    out.println("服务器回复：" + inputLine);
                }
                // 关闭连接
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}